package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.Rule;
import cn.edu.scau.cmi.ema.domain.Rulefield;
import cn.edu.scau.cmi.ema.domain.Site;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("RuleService")
@Transactional

public class RuleServiceImpl extends CmiEmaService implements RuleService {
	public RuleServiceImpl() {
	}

	@Transactional
	public Rule saveRule(Rule rule) {
		Set<Rulefield> existingRulefieldsForRule = new HashSet<Rulefield>();

		Set<Rulefield> selectedRulefieldsForRule = rule.getRulefieldsForRule();

		if (rule.getId() == null) {
			Site site = siteDAO.findSiteById(rule.getSite().getId());

			Rule existingRule = ruleDAO.findRuleByPhysicalPrimaryKey(site.getId(), rule.getName());

			rule.setSite(site);

			if (isEquals(rule, existingRule)) {
				return existingRule;
			}

			rule = ruleDAO.store(rule);
			ruleDAO.flush();

			for (Rulefield relatedRulefield : selectedRulefieldsForRule) {
				relatedRulefield.setRule(rule);
				rulefieldDAO.store(relatedRulefield);
			}
		} else {
			Rule existingRule = ruleDAO.findRuleByPrimaryKey(rule.getId());

			existingRulefieldsForRule = existingRule.getRulefieldsForRule();

			Set<Rulefield> prepareDeleteRulefieldsForRule = new HashSet<Rulefield>();
			Set<Rulefield> prepareAddRulefieldsForRule = new HashSet<Rulefield>();

			prepareDeleteRulefieldsForRule.addAll(selectedRulefieldsForRule);
			prepareDeleteRulefieldsForRule.addAll(existingRulefieldsForRule);

			prepareAddRulefieldsForRule.addAll(selectedRulefieldsForRule);
			prepareAddRulefieldsForRule.addAll(existingRulefieldsForRule);

			prepareDeleteRulefieldsForRule.removeAll(selectedRulefieldsForRule);
			prepareAddRulefieldsForRule.removeAll(existingRulefieldsForRule);

			for (Rulefield relatedRulefield : prepareAddRulefieldsForRule) {
				relatedRulefield.setRule(rule);
				rulefieldDAO.store(relatedRulefield);
			}

			for (Rulefield relatedRulefield : prepareDeleteRulefieldsForRule) {
				relatedRulefield.setRule(null);
				rulefieldDAO.store(relatedRulefield);
			}
			rule = ruleDAO.store(rule);
			ruleDAO.flush();
		}

		rulefieldDAO.flush();
		return rule;
	}

	public void deleteRule(Rule rule) {
		ruleDAO.remove(rule);
		ruleDAO.flush();
	}

	@Transactional
	public void deleteRules(Set<Integer> deleteRulesId) {
		Query query = ruleDAO.createNamedQuery("deleteRulesById", -1, -1);
		query.setParameter(1, deleteRulesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Rule> loadRules() {
		return ruleDAO.findAllRules();

	}

	@Transactional
	public Set<Rule> loadReferenceRules(Set<Rule> rules) {
		Iterator<Rule> rulesIterator = rules.iterator();
		Set<Rule> referencedRules = new HashSet<>();
		while (rulesIterator.hasNext()) {
			Rule currentRule = rulesIterator.next();

			if (!currentRule.getRulefieldsForRule().isEmpty()) {
				referencedRules.add(currentRule);
				continue;
			}
		}
		return referencedRules;
	}

	public Set<Rule> loadRulesByIdSet(Set<Integer> ruleIdSet) {

		Iterator<Integer> ruleIdIterator = ruleIdSet.iterator();
		Set<Rule> ruleSet = new HashSet<>();
		while (ruleIdIterator.hasNext()) {
			Integer id = ruleIdIterator.next();
			Rule currentRule = ruleDAO.findRuleById(id);
			ruleSet.add(currentRule);
		}
		return ruleSet;
	}

	@Transactional
	public List<Rule> findAllRules(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Rule>(ruleDAO.findAllRules(startResult, maxRows));
	}

	@Transactional
	public Rule findRuleByPrimaryKey(Integer id) {
		return ruleDAO.findRuleByPrimaryKey(id);
	}

	@Transactional
	public Integer countRules() {
		return ((Long) ruleDAO.createQuerySingleResult("select count(o) from Rule o").getSingleResult()).intValue();
	}

	@Transactional
	public Integer countRules(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Rule.class);
		return ((Long) ruleDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countRulesByName(String queryName) {
		Query query = ruleDAO.createNamedQuery("countRulesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countRulesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Rule.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadRuleObjectReferencedSet(Rule rule) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (rule.getSite() != null) {

			Set<Integer> siteIds = new HashSet<Integer>();
			siteIds.add(rule.getSite().getId());
			objectReferencedSetMap.put("siteIds", siteIds);
		}

		Set<Integer> rulefieldsIds = new HashSet<Integer>();
		for (Rulefield obj : rule.getRulefieldsForRule()) {

			rulefieldsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("rulefieldsIds", rulefieldsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadRuleClassReferencedSet(Rule rule) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("sites", siteDAO.findAllSites());
		classReferencedSetMap.put("rulefields", rulefieldDAO.findAllRulefields());

		return classReferencedSetMap;
	}

	public boolean isEquals(Rule rule, Object obj) {
		if (obj == rule)
			return true;
		if (!(obj instanceof Rule))
			return false;
		Rule comparedRule = (Rule) obj;
		if (!CheckPropertyEqual(rule.getSite().getId(), comparedRule.getSite().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(rule.getName(), comparedRule.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

